# -*- coding: utf-8 -*-
import json

import chinese2digits as c2d
from itemadapter import ItemAdapter
from redis import Redis
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule

from BooksSipder.items import RomanSpiderItem, InfoSpiderItem


class BooksSpider(CrawlSpider):
    def __init__(self, *a, **kw):
        self.Redis = Redis(host='localhost', port=6379, decode_responses=True)
        super().__init__(*a, **kw)

    name = 'books'
    allowed_domains = ['www.nuomi99.com']
    start_urls = ['https://www.nuomi99.com/book/1/1/5459103.html']

    rules = (
        Rule(LinkExtractor(allow=r'/\d+/\d+'), callback='parse_item', follow=True),  # 内容爬取
    )

    def parse_item(self, response):
        print(
            f"""The target URL information is crawled successfully, the URL is {response.url}, and the return status code is {response.status}""",
            end="\n")
        if response.xpath("""/html/body/div[1]/div/div/div/a[2]/text()""").get():
            items = InfoSpiderItem(
                RomanBook_name=response.xpath("""/html/body/div[1]/div/div/div/a[2]/text()""").get(),
                RomanTitle=response.xpath("""/html/body/div[1]/div/div/div/h1/text()""").get(),
                RomanText="".join(response.xpath("""//*[@id="content"]/text()""").getall()),
            )
        else:
            items = RomanSpiderItem(
                RomanImg_url=response.xpath("""/html/body/div[1]/div/div/div/img/@src""").get(),
                RomanOuter=response.xpath("""/html/body/div[1]/div/div/div/p[1]/text()""").get()[5:],
                RomanKort_inlining=response.xpath("""//*[@id="intro"]/text()""").get().strip(),
                RomanBook_name=response.xpath("""/html/body/div[1]/div/div/div[1]/h1/text()""").get(),
            )
        yield items

    @classmethod
    def get_touch_file_name(cls, touch_file: str) -> str:
        """
        :param touch_file: 文件名
        :except touch_file: 第两百三十二章 喜悦的一天
        :return: 文件名加工，以便文件排序
        """
        Instr = touch_file.split()
        """输出样式选择
                {1} c2d.takeNumberFromString(Instr[0]).get("replacedText")
                输出：第232章


                {2} c2d.takeNumberFromString(Instr[0]) 
                详解: 可选参数列表
                输出：
                {
                  'inputText': '第两百三十二章', 
                  'replacedText': '第232章', 
                  'CHNumberStringList': ['二百三十二'], 
                  'digitsStringList': ['232'], 
                  'errorWordList': [], 
                  'errorMsgList': []
                }

                {3} c2d.takeNumberFromString(Instr[0]).get("digitsStringList")[0]  
                输出：232
        """
        Instr[0] = c2d.takeNumberFromString(Instr[0]).get("replacedText")  # 第n章标题
        return f"{Instr[0]} {''.join(Instr[1:])}"
